package com.numberone.master.modules.sys.web;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.numberone.master.common.config.Global;
import com.numberone.master.common.utils.DateUtils;
import com.numberone.master.common.utils.StringUtils;
import com.numberone.master.common.web.BaseController;
import com.numberone.master.modules.recharge.service.PackageService;
import com.numberone.master.modules.sys.dao.UserDao;
import com.numberone.master.modules.sys.entity.Office;
import com.numberone.master.modules.sys.entity.Role;
import com.numberone.master.modules.sys.entity.User;
import com.numberone.master.modules.sys.service.OfficeService;
import com.numberone.master.modules.sys.service.SystemService;
import com.numberone.master.modules.sys.utils.UserUtils;

import com.numberone.master.modules.news.entity.News;
import com.numberone.master.modules.news.service.NewsService;
import com.numberone.master.modules.profit.entity.AccountInfo;
import com.numberone.master.modules.profit.service.AccountInfoService;
import com.numberone.master.modules.recharge.entity.Package;

/**
 * 代理商Controller
 * 
 * @author chengkang
 * @version 2018-1-15
 */
@Controller
@RequestMapping(value = "${adminPath}/sys/office")
public class OfficeController extends BaseController {

	@Autowired
	private OfficeService officeService;

	@Autowired
	private SystemService systemService;

	@Autowired
	private PackageService packageService;

	@Autowired
	private UserDao userDao;

	@Autowired
	private AccountInfoService accountInfoService;

	@Autowired
	private NewsService newsService;
	
	static  List<Office> childMenu = new ArrayList<Office>();


	@ModelAttribute("office")
	public Office get(@RequestParam(required = false) String id) {
		if (StringUtils.isNotBlank(id)) {
			return officeService.get(id);
		} else {
			return new Office();
		}
	}

	@RequiresPermissions("sys:office:view")
	@RequestMapping(value = { "" })
	public String index(Office office, Model model) {
		// model.addAttribute("list", officeService.findAll());
		return "modules/sys/officeIndex";
	}

	/**
	 * list列表
	 * 
	 * @param office
	 * @param model
	 * @return
	 */
	@RequiresPermissions("sys:office:view")
	@RequestMapping(value = { "list" })
	public String list(Office office, Model model,HttpServletRequest req) {
		
    	
		String id = UserUtils.getUser().getOffice().getId();
		List<String> list_officeId = new ArrayList<String>();
		officeService.getAllOwnAgent(id, list_officeId);
		String s = StringUtils.join(list_officeId.toArray(),",");
		if(StringUtils.isEmpty(s)){
			office.setParentIds(id);
		}else{
			office.setParentIds(s+","+id);
		}
		office.setType("");
		String name = office.getName();
		if(!StringUtils.isBlank(name)){
			office.setName(name);
		}
		List<Office> list = officeService.findAlreadyList(office);
		Office off = UserUtils.getUser().getOffice();
		model.addAttribute("list", list);
		if(StringUtils.isEmpty(name)){
			model.addAttribute("officeId", off.getParentId());
		}else{
			if(list.size() > 0){
				model.addAttribute("officeId", list.get(0).getParentId());
			}
		}
		return "modules/sys/officeList";
	}


	/**
	 * 分配套餐数据
	 * 
	 * @param office_id
	 * @param model
	 * @return
	 */
	@RequiresPermissions("sys:office:distribution")
	@RequestMapping(value = { "packageList" })
	@ResponseBody
	public List<Package> packageList(Integer office_id, Model model) {
		// 获取当前登录代理商id
		Integer id = Integer.valueOf(UserUtils.getUser().getOffice().getId());
		List<Package> list = packageService.packageList(id, office_id);
		return list;
	}

	/**
	 * 
	 * @param fee
	 *            价格
	 * @param taocanId
	 *            套餐id
	 * @param office_id
	 *            所属代理商
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("sys:office:distribution")
	@RequestMapping(value = "distributio")
	public String distributio(String fee, String taocanId, String office_id, RedirectAttributes redirectAttributes) {
		if (StringUtils.isEmpty(taocanId)) {
			addMessage(redirectAttributes, "请选择套餐，分配失败。");
			return "redirect:" + adminPath + "/sys/office/list";
		}
		// 查询套餐信息
		Package pk = packageService.get(taocanId);
		// 查询代理商
		Office o = officeService.get(office_id.replace(",", ""));
		// 获取当前登录代理商id
		User user = UserUtils.getUser();
		Package p = new Package();
		p.setCreateDate(new Date());
		p.setType(pk.getType());
		p.setTctype(pk.getTctype());
		p.setTcId(pk.getTcId());
		p.setPrice(new Double(fee));
		p.setSalePrice(new Double(fee));
		p.setOffice(o);
		p.setCreateBy(user);
		p.setDelFlag("0");
		packageService.insert(p);
		addMessage(redirectAttributes, "分配成功。");
		return "redirect:" + adminPath + "/sys/office/list";
	}

	/**
	 * 打开修改增加代理商
	 * 
	 * @param office
	 * @param model
	 * @return
	 */
	@RequiresPermissions("sys:office:view")
	@RequestMapping(value = "form")
	public String form(Office office, String types, Model model) {
		model.addAttribute("menuList", UserUtils.getMenuList());
		User user = UserUtils.getUser();
		if (office.getParent() == null || office.getParent().getId() == null) {
			office.setParent(user.getOffice());
		}
		if (types.equals("2")) {
			// 查询代理商
			Office o = officeService.get(office.getId());
			if (!o.getId().equals("1")) {
				Office os = officeService.get(o.getParent().getId());
				model.addAttribute("officeParName", os.getName());
				model.addAttribute("parId", os.getId());
			} else {
				model.addAttribute("officeParName", "无");
				model.addAttribute("parId", "0");
			}
			// 查询所属用户
			// office.setUser(systemService.getUser(office.getPrimaryPerson().getId()));
			model.addAttribute("office", office);
			return "modules/sys/officeUpdate";
		} else {
			// 查询代理商
			Office o = officeService.get(office.getParent().getId());
			model.addAttribute("officeParName", o.getName());
			model.addAttribute("parId", o.getId());
			model.addAttribute("office", office);
			return "modules/sys/officeSave";
		}
	}

	/**
	 * 修改
	 * 
	 * @param office
	 * @param model
	 * @param redirectAttributes
	 * @param response
	 * @return
	 */
	@RequiresPermissions("sys:office:edit")
	@RequestMapping(value = "edit")
	public String update(Office office, Model model, RedirectAttributes redirectAttributes,
			HttpServletResponse response) {
		if (!beanValidator(model, office)) {
			return form(office, "2", model);
		}
		office.setUpdateBy(UserUtils.getUser());
		office.setUpdateDate(new Date());
		officeService.update(office);
		addMessage(redirectAttributes, "修改代理商'" + office.getName() + "'成功");
		return "redirect:" + adminPath + "/sys/office/list";
	}

	/**
	 * 增加
	 * 
	 * @param office
	 * @param model
	 * @param redirectAttributes
	 * @param response
	 * @return
	 */
	@RequiresPermissions("sys:office:save")
	@RequestMapping(value = "save")
	public String save(Office office, Model model, RedirectAttributes redirectAttributes,
			HttpServletResponse response) {
		if (!beanValidator(model, office)) {
			return form(office, "1", model);
		}
		office.setCreateDate(new Date());
		office.setCreateBy(UserUtils.getUser());
		officeService.insert(office);
		// 查询添加的代理商
		Office o = officeService.isName(office.getName());
		// 添加用户
		User users = new User();
		users.setCompany(o);
		users.setOffice(o);
		users.setEmail(o.getEmail());
		users.setPhone(o.getContactsPhone());
		users.setMobile(o.getPhone());
		users.setUserType("1");
		users.setCreateBy(o.getUser());
		users.setCreateDate(new Date());
		users.setRemarks("代理商用户");
		users.setName(o.getName());
		users.setDelFlag("0");
		users.setNo("001");
		users.setPassword(SystemService.entryptPassword(office.getNewPassword()));
		users.setLoginName(office.getLoginName());
		userDao.insert(users);
		// 查询添加的用户
		User u = systemService.getUserByLoginName(office.getLoginName());
		// 添加代理角色关联信息
		Role role = new Role();
		role.setDelFlag("0");
		userDao.insertUserRoleInfo(u.getId(), "3");
		// 添加账户信息
		AccountInfo account = new AccountInfo();
		account.setKamt("0");
		account.setOfficeId(Long.valueOf(o.getId()));
		account.setAttype("01");
		account.setZamt("0");
		account.setDamt("0");
		accountInfoService.insert(account);
		// 添加通知信息
		String id = UserUtils.getUser().getOffice().getId();
		News news = new News();
		news.setAcceptUserId(id);
		news.setPushNewsId("2");
		news.setSeeState("0");
		news.setSeeType("0");
		news.setCreateDate(new Date());
		news.setTitle("新增了代理商");
		news.setCount(DateUtils.getDate() + "代理商<" + o.getName() + ">成为您的下级代理商");
		newsService.insert(news);
		addMessage(redirectAttributes, "保存代理商'" + office.getName() + "'成功");
		return "redirect:" + adminPath + "/sys/office/list";
	}

	/**
	 * 删除
	 * 
	 * @param office
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("sys:office:delete")
	@RequestMapping(value = "delete")
	public String delete(Office office, RedirectAttributes redirectAttributes) {
		if (Global.isDemoMode()) {
			addMessage(redirectAttributes, "演示模式，不允许操作！");
			return "redirect:" + adminPath + "/sys/office/list";
		}
		// if (Office.isRoot(id)){
		// addMessage(redirectAttributes, "删除机构失败, 不允许删除顶级机构或编号空");
		// }else{
		officeService.delete(office);
		addMessage(redirectAttributes, "删除机构成功");
		// }
		return "redirect:" + adminPath + "/sys/office/list?id=" + office.getParentId();
	}

	/**
	 * 获取机构JSON数据。
	 * 
	 * @param extId
	 *            排除的ID
	 * @param type
	 *            类型（1：公司；2：部门/小组/其它：3：用户）
	 * @param grade
	 *            显示级别
	 * @param response
	 * @return
	 */
	@RequiresPermissions("user")
	@ResponseBody
	@RequestMapping(value = "treeData")
	public List<Map<String, Object>> treeData(@RequestParam(required = false) String extId,
			@RequestParam(required = false) String type, @RequestParam(required = false) Long grade,
			@RequestParam(required = false) Boolean isAll, HttpServletResponse response) {
		// 当前登录人所属代理商id
		String officeId = UserUtils.getUser().getOffice().getId();
		List<Map<String, Object>> mapList = Lists.newArrayList();
		
		List<String> list_officeId = new ArrayList<String>();
		officeService.getAllOwnAgent(officeId, list_officeId);
		String s = StringUtils.join(list_officeId.toArray(),",");
		Office office = new Office();
		if(StringUtils.isBlank(s)){
			office.setParentIds(officeId);
		}else{
			office.setParentIds(s+","+officeId);
		}
		office.setType("");
		List<Office> list = officeService.findAlreadyList(office);
		Office off = UserUtils.getUser().getOffice();
		for (int i = 0; i < list.size(); i++) {
			Office e = list.get(i);
			if(e.getId().equals("1460493")){
				System.out.println("周伟");
			}
			//if (officeId.compareTo(e.getId()) <= 0) {
				Map<String, Object> map = Maps.newHashMap();
				map.put("id", e.getId());
				map.put("pId", e.getParentId());
				map.put("pIds", e.getParentIds());
				map.put("name", e.getName());
				if (type != null && "3".equals(type)) {
					map.put("isParent", true);
				}
				mapList.add(map);
			//}
		}
		return mapList;
	}

	/**
	 * 判断代理商是否存在
	 * 
	 * @param oldName
	 * @param name
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "isName")
	public String isName(String oldName, String name) {
		if (name != null && name.equals(oldName)) {
			return "true";
		} else if (name != null && officeService.isName(name) == null) {
			return "true";
		}
		return "false";
	}

}
